import { Router } from 'vue-router';
import { useNProgress } from '@vueuse/integrations/useNProgress';
import { useLocale } from '@/locales/useLocale';
import { useAuthStoreWithOut } from '@/store/module/useAuthStore';
import { ElMessage } from 'element-plus';

export const setupRouterGuard = (router: Router) => {
  createPageLoadGuard(router);
  createAuthGuard(router);
};

const { start, done } = useNProgress();

const createPageLoadGuard = (router: Router) => {
  router.beforeEach((to, from) => {
    start();
  });
  router.afterEach((to, from) => {
    // @ts-ignore
    const { t } = useLocale();
    if (to.meta.title && to.meta.title !== '404') {
      document.title = t(to.meta.title);
    }
    done();
  });
};

const authStore = useAuthStoreWithOut();

const createAuthGuard = (router: Router) => {
  // @ts-ignore
  router.beforeEach((to, from) => {
    if (to.meta.requiresAuth && !authStore.isLogged()) {
      ElMessage.error({
        message: '登录失效，请重新登录！',
      });
      return {
        name: 'Login',
        query: { redirect: to.name },
      };
    }
  });
};
